import * as dayjs from "dayjs";
import { genRandomStr, RandomStrTypeConst } from "st-common-core";
import { tripleDesUtil } from "st-common-encrypt";

/**
 * 生成用户账号，生成规则：st + YYYYMMDDHHmmss + 四位随机数
 */
export const genUserAccount = () => {
  return "st"
    + dayjs().format("YYYYMMDDHHmmss")
    + genRandomStr(RandomStrTypeConst.DIGITS, 4);
};

/**
 * 生成随机用户密码加密盐
 *
 * @returns {string} 用户密码加密盐字符串
 */
export const genUserSalt = (): string => {
  return genRandomStr(RandomStrTypeConst.ALL, 16);
}

/**
 * 加密用户密码
 *
 * @param {string} password 用户密码
 * @param {string} salt 盐值
 * @returns {string} 加密后的密码
 */
export const encryptUserPassword = (password: string, salt: string): string => {
  return tripleDesUtil.encrypt({
    data: password,
    key: salt.repeat(2),
    salt: salt
  })
};

/**
 * 验证用户密码
 *
 * @param {string} password 用户输入的密码
 * @param {string} salt 盐值
 * @param {string} encryptedPassword 数据库中存储的加密密码
 * @returns {boolean} true: 密码正确，false: 密码错误
 */
export const verifyUserPassword = (password: string, salt: string, encryptedPassword: string): boolean => {
  const verifyPassword = tripleDesUtil.encrypt({
    data: password,
    key: salt.repeat(2),
    salt: salt
  })
  return verifyPassword === encryptedPassword;
}